package com.xiaofei;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;


public class GameStart extends Application {

    private static final double WIDTH=800,HEIGHT=600;
    private static Canvas canvas = new Canvas(WIDTH,HEIGHT);
    private GraphicsContext context = canvas.getGraphicsContext2D();

    private Image roleImg = new Image("images/role/gegePlus.png",100,150,true,true);
    private Image backGroundImg = new Image("images/background/beijing.jpg",800,600,true,true);
    private double x = 400, y=300;

    static {
        canvas.setLayoutX(0);
        canvas.setLayoutY(0);
    }

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        update();

        AnchorPane anchorPane = new AnchorPane(canvas);
        Scene scene = new Scene(anchorPane);

        scene.setOnKeyPressed(event -> {
            KeyCode code = event.getCode();
            move(code);
        });
        // 设置窗口标题和场景
        primaryStage.setTitle("My Game");
        primaryStage.setScene(scene);
        // 显示窗口
        primaryStage.show();
    }

    //绘制
    private void paint(){
        context.drawImage(backGroundImg,0,0);
        context.drawImage(roleImg,x,y);
    }

    /**
     * 移动方法
     * @param code 移动方向
     */
    private void move(KeyCode code){
        switch (code){
            case UP:
                if (y>=10) y -= 10;
                break;
            case DOWN:
                if (y<=420) y +=10;
                break;
            case LEFT:
                if (x>=10) x -=10;
                break;
            case RIGHT:
                if (x<=700)x +=10;
                break;
            case SPACE:
                y -= 200;
        }
    }

    private void  update(){
        AnimationTimer animationTimer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                paint();
            }
        };
        animationTimer.start();
    }
}
